function bvqx_srf_writeneighbors(fid, varargin)
% bvqx_srf_writeneighbors  - write neighbors to SRF file
%
% FORMAT:       bvqx_srf_parseneighbors(fid, neighbors)
%
% Input fields:
%
%       fid         input file fid (fopen)
%       neighbors   Nx2 cell array with neighbor numbers and lists
%
% See also BVQXfile, bffio, bvqx_srf_parseneighbors
%
% Note: this function uses a compiled function, bvqx_srf_writeneighborsc.

% Version:  v0.7g
% Build:    9101523
% Date:     Oct-15 2009, 11:03 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
   ~isa(fid, 'double') || ...
    isempty(fid) || ...
   ~isreal(fid) || ...
   ~any(fopen('all') == fid(1)) || ...
   ~iscell(varargin{1}) || ...
    isempty(varargin{1}) || ...
    length(size(varargin{1})) ~= 2 || ...
    size(varargin{1}, 2) ~= 2
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or missing argument.' ...
    );
end

% get neighbors stream
try
    neighstream = bvqx_srf_writeneighborsc(varargin{1});
catch
    error( ...
        'BVQXtools:MEXError', ...
        'Error compiling neighbors stream: %s.', ...
        lasterr ...
    );
end

% write neighbors
try
    fwrite(fid, neighstream, 'uint32');
catch
    error( ...
        'BVQXtools:BadFileOrContent', ...
        'Writing of file failed with: ''%s''.', ...
        lasterr ...
    );
end
